package org.simplestudio.c3p0.datasource;

import java.lang.reflect.Method;
import java.util.Properties;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/**   
* @Title: DataSourceFactory.java 
* @Description: 数据源工厂类 
* @author zhengzhq E-Mail:zzq0324@qq.com
* @date 2016年9月30日 上午10:57:33 
*/
public class DataSourceFactory {

    /**
     * 根据配置信息初始化数据源
     * @param prop
     * @return
     * @throws Exception
     */
    @SuppressWarnings("rawtypes")
    public static ComboPooledDataSource initDataSource(Properties prop) throws Exception {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();

        //使用反射进行设置
        Class<ComboPooledDataSource> classz = ComboPooledDataSource.class;
        Method[] methodArr = classz.getMethods();
        for (Method method : methodArr) {
            String methodName = method.getName();
            if (methodName.startsWith("set") && method.getParameterCount() == 1) {
                methodName = methodName.replace("set", "");
                String configKey = "c3p0." + methodName.substring(0, 1).toLowerCase()
                        + methodName.substring(1);
                if (prop.containsKey(configKey)) {
                    try {
                        Object valueObj = prop.getProperty(configKey);
                        Class parameterClass = method.getParameterTypes()[0];
                        if (parameterClass.getName() == "int" || parameterClass == Integer.class) {
                            valueObj = Integer.parseInt(valueObj.toString());
                        }

                        method.invoke(dataSource, valueObj);
                    } catch (Exception e) {
                        System.out.println("method: " + methodName + " invoke fail! error is: "
                                + e.getMessage());
                    }
                }
            }
        }

        return dataSource;
    }

}
